<template>
  <div class="min-h-screen bg-gray-50">
    <!-- 顶部导航栏 -->
    <header class="sticky top-0 z-50 bg-white shadow-md transition-all duration-300">
      <div class="container mx-auto px-4">
        <div class="flex items-center justify-between h-16 md:h-20">
          <!-- Logo -->
          <div class="flex items-center">
            <router-link to="/" class="flex items-center">
              <i class="fas fa-book text-primary text-2xl md:text-3xl mr-2"></i>
              <span class="text-xl md:text-2xl font-bold text-primary" style="font-weight: 700;">书香阁</span>
            </router-link>
          </div>

          <!-- 主导航 - 桌面版 -->
          <nav class="hidden md:flex items-center space-x-8">
            <router-link to="/home" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">首页</router-link>
            <router-link to="/category" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">分类</router-link>
            <router-link to="/bestseller" class="font-medium text-gray-600 hover:text-primary transition-colors py-1">畅销榜</router-link>
            <router-link to="/news" class="font-medium text-primary border-b-2 border-primary py-1">资讯</router-link>
          </nav>

          <!-- 搜索框 -->
          <div class="hidden md:flex items-center flex-1 max-w-md mx-8">
            <div class="relative w-full flex">
              <el-input
                v-model="searchKeyword"
                placeholder="请输入您喜欢的商品"
                class="search-input flex-1"
                @keyup.enter="handleSearch"
              >
                <template #prefix>
                  <i class="fas fa-search text-gray-400"></i>
                </template>
              </el-input>
              <button
                @click="handleSearch"
                class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
              >
                <i class="fas fa-search"></i>
              </button>
            </div>
          </div>

          <!-- 用户工具栏 -->
          <div class="flex items-center space-x-4">
            <button class="relative p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bell text-lg"></i>
              <span class="absolute top-1 right-1 w-2 h-2 bg-red-500 rounded-full"></span>
            </button>
            <button
              @click="goToCart"
              class="relative p-2 text-gray-600 hover:text-primary transition-colors"
            >
              <i class="fas fa-shopping-cart text-lg"></i>
              <span class="absolute -top-1 -right-1 bg-primary text-white text-xs rounded-full w-5 h-5 flex items-center justify-center">{{ cartStore.cartCount }}</span>
            </button>

            <!-- 用户下拉菜单 -->
            <el-dropdown @command="handleCommand">
              <span class="el-dropdown-link cursor-pointer flex items-center">
                <el-avatar :size="32" :src="getImageUrl(userStore.userInfo?.avatar)">
                  <i class="fas fa-user"></i>
                </el-avatar>
                <span class="hidden md:block ml-2 text-gray-600">{{ userStore.userInfo?.username }}</span>
                <i class="fas fa-chevron-down ml-1 text-gray-400"></i>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="profile">个人资料</el-dropdown-item>
                  <el-dropdown-item command="orders">我的订单</el-dropdown-item>
                  <el-dropdown-item command="settings">设置</el-dropdown-item>
                  <el-dropdown-item divided command="logout">退出登录</el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>

            <!-- 移动端菜单按钮 -->
            <button @click="toggleMobileMenu" class="md:hidden p-2 text-gray-600 hover:text-primary transition-colors">
              <i class="fas fa-bars text-xl"></i>
            </button>
          </div>
        </div>

        <!-- 移动端搜索框 -->
        <div class="md:hidden pb-4">
          <div class="flex">
            <el-input
              v-model="searchKeyword"
              placeholder="请输入您喜欢的商品"
              class="search-input flex-1"
              @keyup.enter="handleSearch"
            >
              <template #prefix>
                <i class="fas fa-search text-gray-400"></i>
              </template>
            </el-input>
            <button
              @click="handleSearch"
              class="search-button ml-2 px-4 py-2 text-white rounded-full transition-colors flex items-center justify-center"
            >
              <i class="fas fa-search"></i>
            </button>
          </div>
        </div>
      </div>

      <!-- 移动端导航菜单 -->
      <div v-show="showMobileMenu" class="md:hidden bg-white border-t border-gray-100 shadow-lg">
        <div class="container mx-auto px-4 py-3 space-y-3">
          <router-link to="/home" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">首页</router-link>
          <router-link to="/category" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">分类</router-link>
          <router-link to="/bestseller" class="block py-2 px-3 rounded-lg hover:bg-gray-100 transition-colors">畅销榜</router-link>
          <router-link to="/news" class="block py-2 px-3 rounded-lg bg-primary/10 text-primary font-medium">资讯</router-link>
        </div>
      </div>
    </header>

    <!-- 主要内容 -->
    <main class="container mx-auto px-4 py-6">
      <!-- 面包屑导航 -->
      <nav class="mb-6">
        <ol class="flex items-center space-x-2 text-sm text-gray-500">
          <li><router-link to="/home" class="hover:text-primary">首页</router-link></li>
          <li><i class="fas fa-chevron-right mx-2"></i></li>
          <li><router-link to="/news" class="hover:text-primary">图书资讯</router-link></li>
          <li><i class="fas fa-chevron-right mx-2"></i></li>
          <li class="text-gray-800">{{ article?.title }}</li>
        </ol>
      </nav>

      <div v-if="loading" class="flex justify-center items-center py-20">
        <el-loading-spinner size="large" />
      </div>

      <div v-else-if="!article" class="text-center py-20">
        <i class="fas fa-exclamation-triangle text-6xl text-gray-400 mb-4"></i>
        <h2 class="text-2xl font-bold text-gray-600 mb-4">文章不存在</h2>
        <el-button type="primary" @click="goBack">返回资讯列表</el-button>
      </div>

      <div v-else class="grid grid-cols-1 lg:grid-cols-3 gap-8">
        <!-- 文章主体内容 -->
        <article class="lg:col-span-2">
          <div class="bg-white rounded-xl shadow-sm p-6 md:p-8">
            <!-- 文章头部信息 -->
            <header class="mb-6">
              <div class="flex items-center gap-2 mb-4">
                <span class="bg-primary/10 text-primary text-sm font-medium px-3 py-1 rounded-full">{{ article.category }}</span>
              </div>
              <h1 class="text-2xl md:text-3xl font-bold text-gray-800 mb-4 leading-tight">{{ article.title }}</h1>
              <div class="flex flex-wrap items-center gap-4 text-sm text-gray-500 border-b border-gray-100 pb-4">
                <div class="flex items-center">
                  <i class="fas fa-user mr-2"></i>
                  <span>{{ article.author }}</span>
                </div>
                <div class="flex items-center">
                  <i class="fas fa-calendar mr-2"></i>
                  <span>{{ article.publishDate }}</span>
                </div>
                <div class="flex items-center">
                  <i class="fas fa-eye mr-2"></i>
                  <span>{{ article.views }}</span>
                </div>
              </div>
            </header>

            <!-- 文章封面图片 -->
            <div class="mb-6">
              <img
                :src="article.image"
                :alt="article.title"
                class="w-full h-64 md:h-80 object-cover rounded-lg"
              >
            </div>

            <!-- 文章内容 -->
            <div class="prose prose-lg max-w-none">
              <div class="text-gray-700 leading-relaxed whitespace-pre-line" v-html="article.content"></div>
            </div>

            <!-- 文章底部操作 -->
            <footer class="mt-8 pt-6 border-t border-gray-100">
              <div class="flex items-center justify-between">
                <el-button type="primary" @click="goBack" icon="ArrowLeft">返回列表</el-button>
              </div>
            </footer>
          </div>
        </article>

        <!-- 侧边栏 -->
        <aside class="lg:col-span-1">
          <!-- 相关文章推荐 -->
          <div class="bg-white rounded-xl shadow-sm p-6 mb-6">
            <h3 class="text-lg font-bold text-gray-800 mb-4">相关文章</h3>
            <div class="space-y-4">
              <article
                v-for="relatedArticle in relatedArticles"
                :key="relatedArticle.id"
                class="cursor-pointer group"
                @click="goToArticle(relatedArticle.id)"
              >
                <div class="flex gap-3">
                  <img
                    :src="relatedArticle.image"
                    :alt="relatedArticle.title"
                    class="w-16 h-16 object-cover rounded-lg"
                  >
                  <div class="flex-1">
                    <h4 class="font-medium text-gray-800 group-hover:text-primary transition-colors line-clamp-2 mb-1">{{ relatedArticle.title }}</h4>
                    <p class="text-xs text-gray-500">{{ relatedArticle.publishDate }}</p>
                  </div>
                </div>
              </article>
            </div>
          </div>

          <!-- 热门文章 -->
          <div class="bg-white rounded-xl shadow-sm p-6">
            <h3 class="text-lg font-bold text-gray-800 mb-4">热门文章</h3>
            <div class="space-y-4">
              <article
                v-for="(hotArticle, index) in hotArticles"
                :key="hotArticle.id"
                class="cursor-pointer group"
                @click="goToArticle(hotArticle.id)"
              >
                <div class="flex gap-3">
                  <div class="flex-shrink-0 w-6 h-6 bg-primary text-white text-xs font-bold rounded-full flex items-center justify-center">
                    {{ index + 1 }}
                  </div>
                  <div class="flex-1">
                    <h4 class="font-medium text-gray-800 group-hover:text-primary transition-colors line-clamp-2 mb-1">{{ hotArticle.title }}</h4>
                    <div class="flex items-center text-xs text-gray-500">
                      <i class="fas fa-eye mr-1"></i>
                      <span>{{ hotArticle.views }}</span>
                    </div>
                  </div>
                </div>
              </article>
            </div>
          </div>
        </aside>
      </div>
    </main>

    <!-- 底部页脚 -->
    <footer class="bg-gray-900 text-white py-10 mt-16">
      <div class="container mx-auto px-4">
        <div class="grid grid-cols-1 md:grid-cols-4 gap-8">
          <!-- 关于我们 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">关于书香阁</h3>
            <p class="text-gray-400 text-sm">
              书香阁是专业的网上书店，提供超过10万种图书在线购买，支持快递配送和自提服务，让阅读触手可及。
            </p>
          </div>

          <!-- 快捷链接 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">快捷链接</h3>
            <ul class="space-y-2 text-sm">
              <li><router-link to="/category" class="text-gray-400 hover:text-primary">分类浏览</router-link></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">热门排行</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">最新上架</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">特价促销</a></li>
            </ul>
          </div>

          <!-- 客户服务 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">客户服务</h3>
            <ul class="space-y-2 text-sm">
              <li><a href="#" class="text-gray-400 hover:text-primary">常见问题</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">配送方式</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">支付方式</a></li>
              <li><a href="#" class="text-gray-400 hover:text-primary">退换政策</a></li>
            </ul>
          </div>

          <!-- 联系方式 -->
          <div>
            <h3 class="text-lg font-bold mb-4 text-primary">联系我们</h3>
            <ul class="space-y-3 text-sm">
              <li class="flex items-start">
                <i class="fas fa-map-marker-alt text-primary mt-1 mr-3"></i>
                <span class="text-gray-400">北京市朝阳区建国路88号</span>
              </li>
              <li class="flex items-center">
                <i class="fas fa-phone text-primary mr-3"></i>
                <span class="text-gray-400">400-800-1234</span>
              </li>
            </ul>
          </div>
        </div>

        <!-- 版权信息 -->
        <div class="border-t border-gray-800 mt-8 pt-8 text-center">
          <div class="text-gray-500 text-sm">
            © {{ new Date().getFullYear() }} 书香阁 版权所有
          </div>
        </div>
      </div>
    </footer>

    <!-- 回到顶部按钮 -->
    <BackToTop />
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { useCartStore } from '@/stores/cart'
import { ElMessage } from 'element-plus'
import BackToTop from '@/components/BackToTop.vue'
import { newsAPI } from '@/api/news.js'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()
const cartStore = useCartStore()

// 响应式数据
const searchKeyword = ref('')
const showMobileMenu = ref(false)
const loading = ref(true)
const article = ref(null)

// 相关文章数据
const relatedArticles = ref([])

// 加载文章详情
const loadArticleDetail = async () => {
  const articleId = route.params.id
  if (!articleId) {
    ElMessage.error('文章ID不存在')
    router.push('/news')
    return
  }

  loading.value = true
  try {
    const response = await newsAPI.getNewsDetail(articleId)
    article.value = {
      id: response.data.id,
      title: response.data.title,
      summary: response.data.summary,
      author: response.data.author,
      publishDate: formatDate(response.data.publishTime || response.data.createdAt),
      category: getCategoryFromSummary(response.data.summary),
      image: getImageUrl(response.data.cover),
      views: formatViewCount(response.data.viewCount),
      content: response.data.content
    }

    // 加载相关文章
    loadRelatedArticles()
  } catch (error) {
    console.error('加载文章详情失败:', error)
    ElMessage.error('文章不存在或已下线')
    router.push('/news')
  } finally {
    loading.value = false
  }
}

// 加载相关文章
const loadRelatedArticles = async () => {
  try {
    const response = await newsAPI.getLatestNews(4)
    relatedArticles.value = response.data.map(news => ({
      id: news.id,
      title: news.title,
      summary: news.summary,
      author: news.author,
      publishDate: formatDate(news.publishTime || news.createdAt),
      category: getCategoryFromSummary(news.summary),
      image: getImageUrl(news.cover),
      views: formatViewCount(news.viewCount)
    })).filter(item => item.id !== article.value?.id)
  } catch (error) {
    console.error('加载相关文章失败:', error)
  }
}

// 热门文章数据
const hotArticles = ref([])

// 加载热门文章
const loadHotArticles = async () => {
  try {
    const response = await newsAPI.getPopularNews(5)
    hotArticles.value = response.data.map(news => ({
      id: news.id,
      title: news.title,
      summary: news.summary,
      author: news.author,
      publishDate: formatDate(news.publishTime || news.createdAt),
      category: getCategoryFromSummary(news.summary),
      image: getImageUrl(news.cover),
      views: formatViewCount(news.viewCount)
    })).filter(item => item.id !== article.value?.id)
  } catch (error) {
    console.error('加载热门文章失败:', error)
  }
}

// 方法
const toggleMobileMenu = () => {
  showMobileMenu.value = !showMobileMenu.value
}

const handleSearch = () => {
  if (searchKeyword.value.trim()) {
    ElMessage.info(`搜索功能开发中，搜索关键词：${searchKeyword.value}`)
  }
}

const goToCart = () => {
  router.push('/cart')
}

const goBack = () => {
  router.push('/news')
}

const goToArticle = (articleId) => {
  router.push(`/news/${articleId}`)
}
// 处理下拉菜单命令
const handleCommand = (command) => {
  switch (command) {
    case 'profile':
      router.push('/profile')
      break
    case 'orders':
      router.push('/orders')
      break
    case 'settings':
      router.push('/settings')
      break
    case 'logout':
      handleLogout()
      break
  }
}

// 处理登出
const handleLogout = () => {
  userStore.logout()
  ElMessage.success('已退出登录')
  router.push('/login')
}

// 工具函数
const formatViewCount = (count) => {
  if (!count) return '0'
  if (count >= 1000) {
    return (count / 1000).toFixed(1) + 'k'
  }
  return count.toString()
}

const getCategoryFromSummary = (summary) => {
  if (!summary) return '其他'
  if (summary.includes('推荐') || summary.includes('新书')) return '新书推荐'
  if (summary.includes('访谈') || summary.includes('作者')) return '作者访谈'
  if (summary.includes('阅读') || summary.includes('指南')) return '阅读指南'
  if (summary.includes('行业') || summary.includes('动态')) return '行业动态'
  if (summary.includes('书评') || summary.includes('评论')) return '书评推荐'
  return '其他'
}

const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleDateString('zh-CN')
}

// 获取图片URL
const getImageUrl = (url) => {
  if (!url) return 'https://design.gemcoder.com/staticResource/echoAiSystemImages/f94fa5368ec54a9a1fafd8c376d0aa53.png'

  // 如果是完整的URL，直接返回
  if (url.startsWith('http')) {
    return url
  }

  // 如果是上传的文件路径
  if (url.startsWith('/uploads/')) {
    return `http://localhost:8081/api${url}`
  }

  // 如果是静态资源路径
  if (url.startsWith('/assets/')) {
    return `http://localhost:8081/api${url}`
  }

  // 其他情况，添加API前缀
  return `http://localhost:8081/api${url}`
}

// 生命周期
onMounted(() => {
  loadArticleDetail()
  loadHotArticles()
})
</script>

<style scoped>
/* 自定义样式 */
:root {
  --primary: #FF6B8A;
  --primary-light: #FFB3C6;
  --primary-dark: #E55A7A;
  --secondary: #FFF0F3;
  --accent: #FF8FA3;
  --success: #4CAF50;
  --warning: #FF9800;
  --info: #2196F3;
  --dark: #2D3748;
  --gray: #718096;
  --light-gray: #F7FAFC;
  --white: #FFFFFF;
}

.el-dropdown-link {
  display: flex;
  align-items: center;
  color: #606266;
  transition: color 0.3s ease;
}

.el-dropdown-link:hover {
  color: var(--primary);
}

/* 搜索框样式 */
.search-input :deep(.el-input__wrapper) {
  border-radius: 9999px;
  border: 1px solid #d1d5db;
  transition: all 0.3s ease;
}

.search-input :deep(.el-input__wrapper):hover {
  border-color: var(--primary);
}

.search-input :deep(.el-input__wrapper.is-focus) {
  border-color: var(--primary);
  box-shadow: 0 0 0 2px rgba(255, 107, 139, 0.2);
}

/* 搜索按钮样式 */
.search-button {
  background-color: #FF6B8B !important;
}

.search-button:hover {
  background-color: rgba(255, 107, 139, 0.8) !important;
}

/* 文本截断 */
.line-clamp-1 {
  display: -webkit-box;
  -webkit-line-clamp: 1;
  line-clamp: 1;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-2 {
  display: -webkit-box;
  -webkit-line-clamp: 2;
  line-clamp: 2;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

.line-clamp-3 {
  display: -webkit-box;
  -webkit-line-clamp: 3;
  line-clamp: 3;
  -webkit-box-orient: vertical;
  overflow: hidden;
}

/* 主题色定义 */
.text-primary {
  color: rgb(255, 107, 139) !important;
}

.bg-primary {
  background-color: #FF6B8B !important;
}

.border-primary {
  border-color: #FF6B8B !important;
}

.text-secondary {
  color: var(--secondary);
}

.bg-secondary\/30 {
  background-color: rgba(255, 209, 220, 0.3);
}

.text-accent {
  color: var(--accent);
}

.text-dark {
  color: var(--dark);
}

.hover\:text-primary:hover {
  color: #FF6B8B !important;
}

.bg-primary\/10 {
  background-color: rgba(255, 107, 139, 0.1) !important;
}

.hover\:bg-primary\/10:hover {
  background-color: rgba(255, 107, 139, 0.1) !important;
}

/* 文章内容样式 */
.prose {
  color: #374151;
  max-width: none;
}

.prose h2 {
  color: #1f2937;
  font-weight: 700;
  font-size: 1.5em;
  margin-top: 2em;
  margin-bottom: 1em;
  line-height: 1.3333333;
}

.prose h3 {
  color: #1f2937;
  font-weight: 600;
  font-size: 1.25em;
  margin-top: 1.6em;
  margin-bottom: 0.6em;
  line-height: 1.6;
}

.prose p {
  margin-top: 1.25em;
  margin-bottom: 1.25em;
  line-height: 1.75;
}

.prose strong {
  color: #1f2937;
  font-weight: 600;
}

/* 移动端适配 */
@media (max-width: 768px) {
  .container {
    padding-left: 1rem;
    padding-right: 1rem;
  }

  .prose h2 {
    font-size: 1.25em;
  }

  .prose h3 {
    font-size: 1.125em;
  }
}

/* 卡片悬停效果 */
.card-hover {
  transition: all 0.3s ease;
}

.card-hover:hover {
  transform: translateY(-2px);
  box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
}

/* 加载动画 */
.el-loading-spinner {
  color: var(--primary);
}
</style>
